#include <queue>
#include <pthread.h>

template<class T>
class BlockQueue
{
    static const int defaultnum = 20;
public:
    BlockQueue(int cap = defaultnum)
    {
        _maxcap = cap;
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_pcond, nullptr);
        pthread_cond_init(&_ccond, nullptr);
        _lowwater = _maxcap / 3;
        _highwater = _maxcap / 3 * 2;
    }

    void push(const T& x)
    {
        pthread_mutex_lock(&_mutex);
        while (_que.size() == _maxcap) //防止被伪唤醒的状态 
        {
            pthread_cond_wait(&_pcond, &_mutex); //调用,自动释放锁
        }
        _que.push(x);  //确保生产条件满足才能生产
        //if (_que.size() > _highwater)
        pthread_cond_signal(&_ccond);
        pthread_mutex_unlock(&_mutex);
    }

    T pop()
    {
        pthread_mutex_lock(&_mutex);
        while (_que.size() == 0)
        {
            pthread_cond_wait(&_ccond, &_mutex);
        }
        T tmp = _que.front();
        _que.pop();
        //if (_que.size() < _lowwater)
        pthread_cond_signal(&_pcond);
        pthread_mutex_unlock(&_mutex);
        return tmp;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_pcond);
        pthread_cond_destroy(&_ccond);
    }

private:
    std::queue<T> _que;
    int _maxcap;   //最大容量
    pthread_mutex_t _mutex;
    pthread_cond_t _pcond;
    pthread_cond_t _ccond;
    int _lowwater;
    int _highwater; //控制水位线
};